package com.woniuxy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.entity.ArticleRecord;
import com.woniuxy.entity.DTO.ArticleRecordQueryDTO;
import com.woniuxy.mapper.ArticleRecordMapper;
import com.woniuxy.service.IArticleRecordService;
import com.woniuxy.util.PageResult;
import org.springframework.stereotype.Service;
import java.util.Collection;
import java.util.Date;

/**
 * @Author pml
 * @Date 2025/7/21 10:28
 * @Description TODO
 * 帖子审核记录服务实现
 */
@Service
public class ArticleRecordServiceImpl extends ServiceImpl<ArticleRecordMapper, ArticleRecord> implements IArticleRecordService {

    @Override
    public PageResult<ArticleRecord> pageQuery(ArticleRecordQueryDTO queryDTO) {
        // 创建分页对象
        Page<ArticleRecord> page = new Page<>(queryDTO.getPageNum(), queryDTO.getPageSize());

        // 构建查询条件
        QueryWrapper<ArticleRecord> queryWrapper = new QueryWrapper<>();
        if (queryDTO.getArticleId() != null) {
            queryWrapper.eq("article_id", queryDTO.getArticleId());
        }
        if (queryDTO.getUserId() != null) {
            queryWrapper.eq("user_id", queryDTO.getUserId());
        }
        if (queryDTO.getAuditResult() != null) {
            queryWrapper.eq("audit_result", queryDTO.getAuditResult());
        }
        if (queryDTO.getCreateTimeStart() != null) {
            queryWrapper.ge("create_time", queryDTO.getCreateTimeStart());
        }
        if (queryDTO.getCreateTimeEnd() != null) {
            queryWrapper.le("create_time", queryDTO.getCreateTimeEnd());
        }

        // 按创建时间降序排序
        queryWrapper.orderByDesc("create_time");

        // 执行分页查询
        IPage<ArticleRecord> iPage = baseMapper.selectPage(page, queryWrapper);

        // 封装分页结果
        PageResult<ArticleRecord> pageResult = new PageResult<>();
        pageResult.setPageNum(queryDTO.getPageNum());
        pageResult.setPageSize(queryDTO.getPageSize());
        pageResult.setTotal(iPage.getTotal());
        pageResult.setPages((int) iPage.getPages());
        pageResult.setList(iPage.getRecords());

        return pageResult;
    }

    @Override
    public boolean batchUpdateAuditResult(Collection<String> ids, Integer auditResult, String auditOpinion) {
        if (ids == null || ids.isEmpty()) {
            return false;
        }

        // 创建更新对象
        ArticleRecord record = new ArticleRecord();
        record.setAuditResult(auditResult);
        record.setAuditOpinion(auditOpinion);
        record.setCreateTime(new Date());

        // 构建查询条件
        QueryWrapper<ArticleRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", ids);

        // 执行批量更新
        return baseMapper.update(record, queryWrapper) > 0;
    }
}